package com.gimi.cloud.jimi.queue.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.gimi.cloud.jimi.common.enums.ResponseCodeEnum;
import com.gimi.cloud.jimi.common.exception.MsgException;
import com.gimi.cloud.jimi.common.utils.DateUtil;
import com.gimi.cloud.jimi.common.utils.StringUtil;
import com.gimi.cloud.jimi.commonService.InterfacePlatform.InterfacePlatformRequestService;
import com.gimi.cloud.jimi.dao.dao.User.UserDao;
import com.gimi.cloud.jimi.dao.dao.moreInfo.MoreInfoDao;
import com.gimi.cloud.jimi.dao.dao.moreInfo.MoreInfoLogDao;
import com.gimi.cloud.jimi.dao.dao.sys.SysConfigDao;
import com.gimi.cloud.jimi.dao.redis.IRedisService;
import com.gimi.cloud.jimi.dto.app.moreInfo.CreditcardLoginDTO;
import com.gimi.cloud.jimi.entity.app.moreInfo.MoreInfoEntity;
import com.gimi.cloud.jimi.entity.app.moreInfo.MoreInfoLogEntity;
import com.gimi.cloud.jimi.entity.user.User;
import com.gimi.cloud.jimi.queue.service.FengchaoCreditcardWaterService;
import com.rabbitmq.client.Channel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.Message;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @auther loongs
 * @date 2018/1/16  14:55
 */
@Service
public class FengchaoCreditcardWaterServiceImpl implements FengchaoCreditcardWaterService {

    private static final Logger log = LoggerFactory.getLogger(FengchaoCreditCardEmailServiceImpl.class);
    private final static String INTERFACE_PLATFORM_UNIVERSAL_CREDITCARDWATER = "interface_platform_universal_creditCardWater";

    private IRedisService iRedisService;
    private InterfacePlatformRequestService ipRequestService;
    private MoreInfoDao moreInfoDao;
    private MoreInfoLogDao moreInfoLogDao;
    private UserDao userDao;
    private SysConfigDao sysConfigDao;
    //最大容错次数暂时定为3次
    private final Integer MAXTIMES = 3;

    @Autowired
    public FengchaoCreditcardWaterServiceImpl(IRedisService iRedisService, InterfacePlatformRequestService ipRequestService,
                                              MoreInfoDao moreInfoDao, UserDao userDao, SysConfigDao sysConfigDao,MoreInfoLogDao moreInfoLogDao) {
        this.iRedisService = iRedisService;
        this.ipRequestService = ipRequestService;
        this.moreInfoDao = moreInfoDao;
        this.userDao = userDao;
        this.sysConfigDao = sysConfigDao;
        this.moreInfoLogDao=moreInfoLogDao;
    }

    @Override
    public void reveiveCreditcardWaterData(Message message, Channel channel, CreditcardLoginDTO creditcardLoginDTO) throws Exception {
        //校验
        log.info("验证参数");
        if (creditcardLoginDTO == null || StringUtil.isBlank(creditcardLoginDTO.getUserId()) || StringUtil.isBlank(creditcardLoginDTO.getSurnameSid())) {
            throw new MsgException(ResponseCodeEnum.INTERFACE_ERROR, "蜂巢信用卡流水队列信息，入参错误！");
        }
        User user = userDao.getUserByUserId(creditcardLoginDTO.getUserId());
        if (user == null) {
            throw new MsgException(ResponseCodeEnum.ERR_USER_INVALID);
        }
        //查询该用户之前是否有获取过信用卡邮箱账单，需要获取状态为获取中
        MoreInfoEntity moreInfoEntity = moreInfoDao.getMoreInfoByUserIdAndTypeAndData(creditcardLoginDTO.getUserId(),4,1);
        if (moreInfoEntity == null || moreInfoEntity.getGetdataErrorTimes() >= MAXTIMES) {
            throw new MsgException(ResponseCodeEnum.CREDITCARDWATER_DATA_ERROR_TIMES_IS_OUT_OF_TIMES);
        }
        MoreInfoLogEntity moreInfoLogEntity=new MoreInfoLogEntity();
        //如果sessiontoken不存在，说明已经是000的状态，所以直接抓取
        //如果sessiontoken存在，需要先调用查询接口
        if (!StringUtil.isBlank(creditcardLoginDTO.getSessionToken())) {
            //获取状态，状态为000就可以解析,100代表登录中所以在此请求，其他的代表失败
            JSONObject glbody = getStatus(creditcardLoginDTO);
            String status = glbody.getString("status");
            String errors = glbody.getString("errors");
            if ("000".equals(status)) {
                getDataReport(creditcardLoginDTO, moreInfoEntity, user,moreInfoLogEntity);
            } else if ("100".equals(status)||"201".equals(status)) {
                channel.abort();
            } else {
                moreInfoEntity.setGetdata("3");
                moreInfoEntity.setGetdataErrorTimes(moreInfoEntity.getGetdataErrorTimes() + 1);
                moreInfoEntity.setUpdateUid(user.getUserId());
                moreInfoEntity.setUpdateUname(user.getAddUname());
                moreInfoEntity.setUpdateTime(DateUtil.getNow());
                moreInfoEntity.setBaRemark(errors);
                moreInfoDao.updateByPrimaryKey(moreInfoEntity);
                //存入日志
                moreInfoLogEntity.setRequestData(creditcardLoginDTO.toString());
                moreInfoLogEntity.setResponseData(glbody.toJSONString());
                moreInfoLogEntity.setType("4");
                moreInfoLogEntity.setUserId(creditcardLoginDTO.getUserId());
                moreInfoLogEntity.setAddTime(DateUtil.getNow());
                //抓取状态（1成功，2失败）
                moreInfoLogEntity.setStatus(2);
                moreInfoLogDao.insertSelective(moreInfoLogEntity);
            }
        } else {
            getDataReport(creditcardLoginDTO, moreInfoEntity, user,moreInfoLogEntity);
        }
    }

    /**
     * 抓取报告
     *
     * @param creditcardLoginDTO
     * @param moreInfoEntity
     * @param user
     * @throws Exception
     */
    private void getDataReport(CreditcardLoginDTO creditcardLoginDTO, MoreInfoEntity moreInfoEntity, User user,MoreInfoLogEntity moreInfoLogEntity) throws Exception {
        log.info("抓取信用卡流水信息开始");
        String creditCardWater = sysConfigDao.getConfigByKey(INTERFACE_PLATFORM_UNIVERSAL_CREDITCARDWATER);
        JSONObject fgJson = JSON.parseObject(creditCardWater);
        JSONObject getcreditsreport = fgJson.getJSONObject("fengchao_bankonline_getcreditsreport");
        JSONObject glBody = getcreditsreport.getJSONObject("body");
        glBody.put("surnameSid", creditcardLoginDTO.getSurnameSid());

        getcreditsreport.put("body", glBody);
        log.info("封装入参结束：" + getcreditsreport.toJSONString());

        log.info("请求开始");
        String sendApiPost = ipRequestService.sendApiPost(getcreditsreport.toJSONString());

        JSONObject reportJson = JSON.parseObject(sendApiPost);
        JSONObject reportbody = reportJson.getJSONObject("body");
        JSONObject data = reportbody.getJSONObject("data");
        String type = reportbody.getString("type");

        //存入日志
        moreInfoLogEntity.setAddTime(DateUtil.getNow());
        moreInfoLogEntity.setResponseData(sendApiPost);
        moreInfoLogEntity.setRequestData(getcreditsreport.toJSONString());
        moreInfoLogEntity.setUserId(user.getUserId());
        moreInfoLogEntity.setType("4");

        //只有type为1的时候为成功，其他情况都是失败
        if (reportbody != null && "1".equals(type)) {
            //存入数据
            moreInfoEntity.setReportData(data.getString("ossUrl"));
            moreInfoEntity.setGetdataErrorTimes(0);
            moreInfoEntity.setGetdata("2");
            moreInfoEntity.setGetdataTime(DateUtil.getNow());

            //TODO 有效时长，等风控规则
            moreInfoEntity.setReportEffectionBegin(DateUtil.getNow());
            moreInfoEntity.setReportEffectionEnd(DateUtil.getLateYear(1));
            moreInfoEntity.setBaRemark("");

            //抓取状态（1成功，2失败）
            moreInfoLogEntity.setStatus(1);
        } else {
            moreInfoEntity.setGetdata("3");
            moreInfoEntity.setGetdataErrorTimes(moreInfoEntity.getGetdataErrorTimes() + 1);

            //抓取状态（1成功，2失败）
            moreInfoLogEntity.setStatus(2);
        }
        moreInfoLogDao.insertSelective(moreInfoLogEntity);

        moreInfoEntity.setUpdateUid(user.getUserId());
        moreInfoEntity.setUpdateUname(user.getAddUname());
        moreInfoEntity.setUpdateTime(DateUtil.getNow());
        moreInfoDao.updateByPrimaryKey(moreInfoEntity);
    }


    /**
     * 获取状态
     *
     * @param creditcardLoginDTO
     * @return
     * @throws Exception
     */
    private JSONObject getStatus(CreditcardLoginDTO creditcardLoginDTO) throws Exception {
        String creditCardWater = sysConfigDao.getConfigByKey(INTERFACE_PLATFORM_UNIVERSAL_CREDITCARDWATER);
        JSONObject fgJson = JSON.parseObject(creditCardWater);
        JSONObject getloginstatus = fgJson.getJSONObject("fengchao_bankonline_getloginstatus");
        JSONObject glBody = getloginstatus.getJSONObject("body");
        glBody.put("sessionToken", creditcardLoginDTO.getSessionToken());
        getloginstatus.put("body", glBody);

        String glRep = ipRequestService.sendApiPost(getloginstatus.toJSONString());
        JSONObject glRepJson = JSON.parseObject(glRep);
        JSONObject glbody = glRepJson.getJSONObject("body");
        return glbody;
    }

}
